package com.example.videopractice.aduiorecord

import android.Manifest
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import com.example.base.base.BaseBindingActivity
import com.example.base.util.ALog
import com.example.videopractice.databinding.ActivityAudioRecordBinding
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream

/**
 *  AudioRecord API详解及应用 demo
 */
class AudioRecordActivity : BaseBindingActivity<ActivityAudioRecordBinding>() {

    private var audioRecord: AudioRecord? = null
    private var recordBufSize: Int = 0
    private val frequency = 44100
    private val channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO
    private val encodingBitRate = AudioFormat.ENCODING_PCM_16BIT
    private var isRecording = false
    private var audioFilePath = ""
    private var recordingThread: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding.btnStart.setOnClickListener {
            createAudioRecordAndStart()
        }

        binding.btnStop.setOnClickListener {
            stopAudioRecord()
        }
        binding.btnAdd.setOnClickListener {
            GlobalScope.launch (IO){
                val sourcePath = Environment.getExternalStorageDirectory().absolutePath +
                        File.separator + "test.wav"
                val targetPath =  Environment.getExternalStorageDirectory().absolutePath +
                        File.separator + "test1.wav"

                val util = PcmToWavUtil(recordBufSize, frequency, channelConfiguration)
                util.pcmToWav(sourcePath, targetPath)
                ALog.e("xiao", "转换完成")
            }

        }
    }

    private fun createAudioRecordAndStart() {
        recordingThread = GlobalScope.launch {
            requestMultiplePermissions.launch(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO
                )
            )

            runCatching {
                recordBufSize = AudioRecord.getMinBufferSize(
                    frequency,
                    channelConfiguration,
                    encodingBitRate
                )
                audioRecord = AudioRecord(
                    MediaRecorder.AudioSource.MIC,
                    frequency,
                    channelConfiguration,
                    encodingBitRate,
                    recordBufSize
                )

                val buffer = ByteArray(recordBufSize)

                audioRecord?.startRecording()
                isRecording = true
                audioFilePath = Environment.getExternalStorageDirectory().absolutePath + File.separator + "test.wav"
                val audioFile = File(audioFilePath)
                ALog.e("xiao", "audio path: ${audioFile.absoluteFile}")
                if (audioFile.exists()) audioFile.delete()

                val fileOutputStream = FileOutputStream(audioFile)
                fileOutputStream.use {
                    while (isRecording) {
                        val readBytes = audioRecord?.read(buffer, 0, recordBufSize)
                        ALog.e("xiao", "读取的音频数据:$readBytes")
                        it.write(buffer)
                    }
                }

            }.onFailure {
                ALog.e("xiao error", it.message)
                it.printStackTrace()
            }
        }

    }

    private fun stopAudioRecord() {
        isRecording = false
        audioRecord?.stop()
        audioRecord?.release()
        audioRecord = null
        recordingThread?.cancel()
    }
}